import { createRouter,BeforeEachResult } from '@gowiny/uni-router'
import PAGE_DATA from '@/pages.json';
import store from '@/store'

const router = createRouter({
    pageData:PAGE_DATA
})

router.beforeEach(async (to,from)=>{
    console.log('beforeEach 1 ,',to,from)
    const state:any = store.state
    if(!state.app.inited){
        console.debug('正在初始化app')
        uni.showLoading({
            title:'正在初始化app'
        })
        const inited = await store.dispatch("app/init")
        uni.hideLoading()
        console.debug('app初始化完成')
        uni.showToast({
            title:'app初始化完成'
        })
    }

})

router.beforeEach(async (to,from)=>{
    console.log('beforeEach 2 ,',to,from)

    const state:any = store.state
    if(!state.user.logined && to.path?.startsWith("/pages/user/")){
        console.log('您还未登录，请先登录')
        return {
            to:{//需要跳转的新页面
                path:'/pages/login/login',
                query:{
                    url:to.fullPath
                }
            },
            navType:'push'//跳转方式

        }
    }

})

router.beforeEach(async (to,from)=>{
    console.log('beforeEach 3 ,',to,from)

    return new Promise<BeforeEachResult>((success,fail)=>{
        console.debug('正在处理其他业务')

        setTimeout(function(){
            console.debug('其他业务处理完成')
            success(true)
        },100)
    })

})


router.afterEach((to,from)=>{
    console.log('afterEach 1 ,',to,from)
})

router.afterEach(async (to,from)=>{
    console.log('afterEach 2 ,',to,from)
    return new Promise<BeforeEachResult>((success,fail)=>{
        setTimeout(function(){
            console.log('afterEach 已等待3秒，开始下一步')
            success(true)
        },100)
    })

})

export default router
